/**
 * Created by liuyu on 30/10/2016.
 */
'use strict';

const nunjuck = require('nunjucks');

function createEnv(path, opts) {
    var
        autoescape = opts.autoescape,
        noCache = opts.noCache || false,
        watch = opts.watch || false,
        throwOnUndefined = opts.throwOnUndefined || false,
        env = new nunjuck.Environment(
            new nunjuck.FileSystemLoader(path || 'views', {
                noCache: noCache,
                watch: watch
            }), {
                autoescape: autoescape,
                throwOnUndefined: throwOnUndefined
            }
        );
    if (opts.filters) {
        for (let f in opts.filters) {
            env.addFilter(f, opts.filters[f]);
        }
    }
    return env;
}

function templet(path, opts) {
    var env = createEnv(path, opts);
    return async (ctx, next)=> {
        ctx.render = (view, model)=> {
            ctx.response.body = env.render(view, Object.assign({}, ctx.state || {}, model || {}))
            ctx.response.type = 'text/html';
        }
        await next();
    }
}

module.exports = templet;
